package org.codeart.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.codeart.common.dto.TokenResult;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

public class JwtUtils {

    // 盐值
    private static final String SALT = "13770389674";

    private static final String JWT_KEY_PHONE = "passengerPhone";

    private static final String JWT_IDENTITY = "identity";

    private static final String JWT_TOKEN_TYPE = "tokenType";

    private static final String JWT_TOKEN_TIME = "tokenTime";

    /**
     * 生成token，一天过期
     */
    public static String generateToken(String phone, String identity, String tokenType) {
        Map<String, String> map = new HashMap<String, String>() {{
            put(JWT_KEY_PHONE, phone);
            put(JWT_IDENTITY, identity);
            put(JWT_TOKEN_TYPE, tokenType);
            // 加一个时间字段，防止生成token一样
            put(JWT_TOKEN_TIME, LocalDateTime.now().toString());
        }};
//        Calendar calendar = Calendar.getInstance();
//        calendar.add(Calendar.DATE, 1);
//        Date date = calendar.getTime();

        // 填充数据负载
        JWTCreator.Builder builder = JWT.create();
        map.forEach(builder::withClaim);

//        builder.withExpiresAt(date);
        return builder.sign(Algorithm.HMAC256(SALT));
    }

    /**
     * 解析token
     */
    public static TokenResult parseToken(String token) {
        DecodedJWT jwt = JWT.require(Algorithm.HMAC256(SALT)).build().verify(token);
        String phone = jwt.getClaim(JWT_KEY_PHONE).asString();
        String identity = jwt.getClaim(JWT_IDENTITY).asString();
        TokenResult tokenResult = new TokenResult();
        tokenResult.setPhone(phone).setIdentity(identity);
        return tokenResult;
    }

    /**
     * 校验token，主要判断token是否异常
     *
     * @param token
     * @return
     */
    public static TokenResult checkToken(String token) {
        TokenResult tokenResult;
        try {
            tokenResult = JwtUtils.parseToken(token);
        } catch (Exception e) {
            return null;
        }
        return tokenResult;
    }

    public static void main(String[] args) {
        String phone = "13770366963";
        String identity = "driver";
        String s = generateToken(phone, identity, "accessToken");
        System.out.println(s);
        TokenResult tokenResult = parseToken(s);
        System.out.println("手机号：" + tokenResult.getPhone());
        System.out.println("身份：" + tokenResult.getIdentity());
    }
}

